<?php

namespace app\backend\controller;

use app\backend\model\SysUser;
use app\component\BaseController;
use support\Redis;
use app\component\RedisKey;
use support\Request;
use support\XunshanContainer;

class LoginController implements BaseController
{
    public function actionIndex(Request $request)
    {
        // 如果不是访客，直接跳转
        if (!XunshanContainer::user()->getIsGuest()) {
            return redirect('/backend/index/index');
        }
        return view('login');
    }

    public function actionLogin(Request $request)
    {
        $phone = $request->post('username');
        $rawPwd = $request->post('password');
        $rememberMe = $request->post('rememberMe', false);

        /** @var SysUser $sysUser */
        $sysUser = SysUser::where('phone', $phone)->first();
        if (!$sysUser) {
            return json_error('请输入正确的手机号！');
        }

        if ($sysUser->status == 1) {
            //禁用状态
            return json_error('您的账号已经被管理员禁用！');
        }

        if (!password_verify($rawPwd, $sysUser->password_hash)) {
            return json_error('请输入正确的密码！');
        }

        $isLoginSuccess = XunshanContainer::user()->login($sysUser, $rememberMe ? 3600 * 24 * 7 : 0);
        if ($isLoginSuccess) {
            $ip = $request->getRealIp();
            $sysUser->login_ip = $ip;
            $sysUser->login_date = time();
            $sysUser->save();
            return json_success('登录成功');
        }
        return json_error('登录失败，请联系管理员！');
    }

    public function actionUnlock(Request $request)
    {
        $auid = $request->post('auid');
        $rawPwd = $request->post('password');

        /** @var SysUser $sysUser */
        $sysUser = SysUser::query()->where('auid', $auid)->first();
        if (!$sysUser) {
            return json_error('请输入正确的手机号！');
        }

        if ($sysUser->status == 1) {
            //禁用状态
            return json_error('您的账号已经被管理员禁用！');
        }

        if (!password_verify($rawPwd, $sysUser->password_hash)) {
            return json_error('请输入正确的密码！');
        }

        Redis::del(RedisKey::XUNSHAN_USER_LOCK . $auid);
        return json_success('解锁成功');
    }

    public function actionLogout(Request $request)
    {
        Redis::del(RedisKey::XUNSHAN_USER_LOCK . XunshanContainer::user()->getIdentity()->getId());
        XunshanContainer::user()->logout();
        return redirect('/backend/login/index');
    }
}
